package main

import (
	"flag"
	"fmt"
	"github.com/pborman/uuid"
	"github.com/upmio/horus-agent/hclient"
	"github.com/upmio/horus-agent/log"
	"github.com/upmio/horus-agent/model"
	"os"
	"sync"
	"time"
)

var (
	Pnum    int
	Pdata   int
	wg      sync.WaitGroup
	Logfile = flag.String("logfile", "/var/log/horus-plymetricclient.log", "the log file ")
	Debug   = flag.Bool("debug", false, "debug model ,write log to std.err")
)

func getMetricSlice(endpoint string) *model.DataPoint {
	metricslice := []*model.MetricPoint{
		&model.MetricPoint{
			Endpoint:  endpoint,
			Metric:    "metric.test.int",
			Value:     int64(3456),
			Tags:      endpoint,
			Timestamp: int64(time.Now().Unix()),
			HostId:    endpoint,
		},

		&model.MetricPoint{
			Endpoint:  endpoint,
			Metric:    "node.bond0.network_input",
			Value:     float64(34.56),
			Tags:      endpoint,
			Timestamp: int64(time.Now().Unix()),
			HostId:    endpoint,
		},

		&model.MetricPoint{
			Endpoint:  endpoint,
			Metric:    "node.bond0.network_output",
			Value:     float64(56.56),
			Tags:      endpoint,
			Timestamp: int64(time.Now().Unix()),
			HostId:    endpoint,
		},

		&model.MetricPoint{
			Endpoint:  endpoint,
			Metric:    "metric.str.test",
			Value:     "testing",
			Tags:      endpoint,
			Timestamp: int64(time.Now().Unix()),
			HostId:    endpoint,
		},
	}

	metricdata := &model.DataPoint{
		Persistence: false,
		Uuid:        uuid.New(),
		Type:        model.METIRCPOINT_DATA,
		DataObj:     metricslice,
	}
	return metricdata
}

func produceMetric() {
	defer wg.Done()

	endpoint := uuid.New()
	log.Info("run  one Metric product:", endpoint)
	for i := 0; i < Pdata; i++ {
		data := getMetricSlice(endpoint)
		hclient.SendDataByQue(data)
		time.Sleep(1 * time.Second)
	}

	log.Info(endpoint, ":run ok")
}

func main() {

	flag.IntVar(&Pnum, "pnum", 10, "")
	flag.IntVar(&Pdata, "pdata", 100000, "")
	flag.Parse()

	if *Debug {
		if err := log.LogInit("debug", os.Stderr); err != nil {
			fmt.Println("log init fail", err)
			return
		}
	} else {
		logfd, err := os.OpenFile(*Logfile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
		if err != nil {
			fmt.Println("open logfile fail")
			return
		}
		defer logfd.Close()
		if err := log.LogInit("info", logfd); err != nil {
			fmt.Println("log init fail", err)
			return
		}
	}

	//sender init
	hclient.RunInit(3000, 300)

	for i := 0; i < Pnum; i++ {
		wg.Add(1)
		go produceMetric()
	}

	wg.Wait()

}
